package com.woniuxy.utils;

import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@Component
public class MinioUtil {

    private final MinioClient minioClient;

    public MinioUtil(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    // 创建存储桶
    public void createBucket(String bucketName) throws MinioException, IOException, NoSuchAlgorithmException, InvalidKeyException {
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    // 上传文件（MultipartFile）
    public String uploadFile(String bucketName, MultipartFile file) throws Exception {
        String objectName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build()
        );
        return objectName; // 返回存储在 MinIO 中的文件名
    }

    // 下载文件（返回字节数组）
    public byte[] downloadFile(String bucketName, String objectName) throws MinioException, IOException {
        try (InputStream stream = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build()
        )) {
            return IOUtils.toByteArray(stream);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    // 删除文件
    public void deleteFile(String bucketName, String objectName) throws MinioException, IOException, NoSuchAlgorithmException, InvalidKeyException {
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build()
        );
    }

    // 列举存储桶
    public List<String> listBuckets() throws MinioException, IOException, NoSuchAlgorithmException, InvalidKeyException {
        List<String> buckets = new ArrayList<>();
        for (Bucket bucket : minioClient.listBuckets()) {
            buckets.add(bucket.name());
        }
        return buckets;
    }

    // 列举存储桶中的对象
    public List<String> listObjects(String bucketName) throws MinioException, IOException, NoSuchAlgorithmException, InvalidKeyException {
        List<String> objects = new ArrayList<>();
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder()
                        .bucket(bucketName)
                        .build()
        );
        for (Result<Item> result : results) {
            objects.add(result.get().objectName());
        }
        return objects;
    }
}
